$(function(){
	/**
     * 分页初始条件
     */
    var total = 1;//分页总页面数
    var total_count = 1;//分页总记录数
    var currentPage = 1;//当前页
    var pageSize = pageOption.pageSize;//每页显示的记录数
    var idList = [];//批量选择id所存的数组
    /**
     * 页面初始化
     */
    function init(){
        myPagination();
        bindEvent();
    }

    /**
     * 事件绑定
     */
    function bindEvent(){
    	//根据条件查询商品信息
    	$('.search-button').click(function(){
    		render(true,1,pageSize);
            return false;
		});
    	
        //enter键盘事件
        $(".search-param-form select").keydown(function(event){
            event = event ? event: window.event;
            if(event.keyCode == 13){
                render(true,1,pageSize);
                return false;
            }
        });
        
      //批量删除
        $(".content .right-section .delete-batch").click(function(){
        	var ids = idList.join(',');
            if(ids == ""){
        		$("#myModal .modal-body").html("<p class='text-danger'>您尚未选择要删除的选项，请先选择！</p>");
                $("#myModal").modal('show');
                //定时器，1.5秒后模态框自动关闭
                setTimeout(function(){
                    $("#myModal").modal('hide');
                },1500);
        	}else{
	            myConfirmModal("确定要批量删除优惠券吗？",function(){
		            $.ajax({
		                url:"deleteCoupon",
		                type:"post",
		                data:{"ids":ids},
		                dataType:"json",
		                beforeSend:function(xhr){
		                    //显示“加载中。。。”
		                    $("#loading").modal('show');
		                },
		                complete:function(){
		                    //隐藏“加载中。。。”
		                    $("#loading").modal('hide');
		                },
		                success:function(json,statusText){
		                    if(json.errorCode == 0){
		                    	if(currentPage != 1 && (total_count - idList.length) % pageSize == 0){
	                                currentPage = currentPage - 1;
	                            }
	                            idList = [];//初始化idList的值
	                            render(true,currentPage,pageSize);
		                    }else if(json.errorCode == 2){
		                        //优惠券已被领取且尚未使用时，删除前再确认
		                        $("#myConfirmModal").modal('hide');
		                        myConfirmModal(json.errorInfo,function(){
		                        	$.ajax({
		        		                url:"deleteCoupon",
		        		                type:"post",
		        		                data:{"ids":ids, "isAgree":1},
		        		                dataType:"json",
		        		                beforeSend:function(xhr){
		        		                    //显示“加载中。。。”
		        		                    $("#loading").modal('show');
		        		                },
		        		                complete:function(){
		        		                    //隐藏“加载中。。。”
		        		                    $("#loading").modal('hide');
		        		                },
		        		                success:function(json,statusText){
		        		                    if(json.errorCode == 0){
		        		                    	if(currentPage != 1 && (total_count - idList.length) % pageSize == 0){
		        	                                currentPage = currentPage - 1;
		        	                            }
		        	                            idList = [];//初始化idList的值
		        	                            render(true,currentPage,pageSize);
		        		                    }else{
		        			                    responseTip(1,json.errorInfo);
	        			                    }
		        		                },
		        		                error:errorResponse
		                        	});
		                        	$("#deleteConfirmModal").modal('hide');
		                        },'#deleteConfirmModal');
	                        }else{
		                        responseTip(1,json.errorInfo);
		                    }
		                },
		                error:errorResponse
		            });
	            });
        	}
        });
    }
    
    
    /**
     * 获取模糊参数
     */
    function getSelectInfo(){
        var selectInfo = {
            is_use : $(".search-area #is_use").val()
        };
        return selectInfo;
    }
    
    
    /**
     * 分页显示方法
     */
    function myPagination(){
        render(true,1,pageSize);
        //调用公共分页方法
        pagination("#page-selection",{pageSize:pageSize,total:total},render);

    }
    
    
    /**
     * 分页动态渲染数据
     * @param async ajax请求是否异步
     * @param pageIndex 当前显示页
     * @param pageSize 每页显示记录数
     */
    function render(async,pageIndex,pageSize){
        var selectInfo = getSelectInfo();
        selectInfo.pageIndex = pageIndex;
        selectInfo.pageSize = pageSize;
        $.ajax({
            async:async,
            type:'post',
            url:'pagingCoupon',
            data:selectInfo,//从1开始计数
            dataType:'json',
            success:function(json){
                var html ='';
                if(json.errorCode == 0){
                    total = json.data.pageInfo.total_page;
                    total_count = json.data.pageInfo.total_count;
                    $("#page-selection").bootpag({total:total,total_count:total_count});//重新计算总页数

                    currentPage = json.data.pageInfo.current_page;
                    var myList = json.data.dataList;

                    html+='<tr><th class="th1"><input type="checkbox" class="select-all my-icheckbox"></th><th class="th1">序号</th><th class="th2">名称</th><th class="th3">面额/折扣</th><th class="th3">单用户上限</th><th class="th5">简单描述</th><th class="th6">已领取</th><th class="th7">剩余量</th><th class="th8">活动起止时间</th><th class="th3">所属商城</th><th class="th9">状态</th><th class="th10">操作</th></tr>';
                    var colspan = $(html).find("th").length;
                    for(var i = 0; i < myList.length;i++){
                        var obj = myList[i];
                        var num = (pageIndex-1) * pageSize + i+1;
                        var id = obj.id;
                        var name = obj.name;
                        var value = obj.value;
                        var discount = obj.discount;
                        var user_limit = obj.user_limit;
                        var description = obj.description;
                        var get_quantity = obj.get_quantity;
                        var spare_quantity = obj.spare_quantity;
                        var start_date = obj.valid_start;//起始日期
                        var end_date = obj.valid_end;//截止日期
                        var type = obj.type;
                        var type_text = '';
                        if(type == 1){
                        	type_text = '拼团商城';
                        }else if(type == 2){
                        	type_text = '秒杀商城';
                        }
                        else if(type==3){
                            type_text="百货商城";
                        }
                        var user_type = obj.use_type;                      
                        var showInfo = value;                       
                        var is_use = obj.is_use;
                        var checked = (idList.indexOf(id) >= 0) ? "checked":"";//判断当前记录先前有没有被选中

                        html+='<tr>'
                        	+'<td><input type="checkbox" class="select-single my-icheckbox" value="'+id+'" '+checked+'></td>'
                            +'<td>'+ num+'</td>'
                            +'<td>'+ name +'</td>'
                            +'<td>'+showInfo+'</td>'
                            +'<td>'+user_limit+'</td>'
                            +'<td>'+description+'</td>'
                            +'<td>'+get_quantity+'</td>'
                            +'<td>'+spare_quantity+'</td>'
                            +'<td>'+start_date+'~'+end_date+'</td>'
                            +'<td>'+type_text+'</td>'
                            +'<td>'
                            + (is_use == 1?"<span style='color:green;'>已启用</span>":"<span style='color:red;'>已停用</span>") 
                            +'</td>'
                            +'<td>'
                            +(getValue.update() == 1 ? '<a class=" btn btn-primary btn-xs edit" href="editCoupon?id='+id+'">编辑</a>':'')
                            +(getValue.isGet()==1 ? '<a class=" btn btn-primary btn-xs" href="userCouponList?id='+id+'">领取列表</a>':'')
                            +(getValue.enable()==1 ? (is_use == 0?'<a href="javascript:;" data-is_use="1" class="btn btn-success btn-xs setuse" data-id="'+id+'">启用</a><a href="javascript:;"  class="btn btn-default btn-xs delete"  data-id="'+id+'">删除</a>':'<a href="javascript:;" data-is_use="0" class="btn btn-default btn-xs setuse" data-id="'+id+'">停用</a>'):'')
                            +'</td>'
                            +'</tr>';

                    }

                    if(myList.length == 0){
                        html += '<tr><td colspan="'+colspan+'"><p class="text-danger">暂无数据。</p></td></tr>';
                    }
                    $("#list-table tbody").html(html);
                    myCheck();
                    batchSelect(idList,".inner-section #list-table .select-all",".inner-section #list-table .select-single");
                    $("#list-table .delete").click(deleteCoupon);
                    $("#list-table .setuse").click(setUse);
                }else{
                    responseTip(json.errorCode,json.errorInfo,1500);
                }

            },
            error:errorResponse
        });
    }

    
    /**
     * 开启/关闭
     */
    function setUse(){
        var id = $(this).attr("data-id");
        var is_use = $(this).attr("data-is_use");
        $.ajax(
            {
                type:"post",
                url:"useCoupon",
                data:{"id":id,"is_use":is_use},
                dataType:"json",
                success:function(json,statusText){
                    if(json.errorCode == 0){
                        render(true,currentPage,pageSize);
                    }else{
                        responseTip(json.errorCode,json.errorInfo,1500);
                    }
                },
                error:errorResponse
            }
        );
    }


    //删除
    function deleteCoupon(){
        var id = $(this).attr("data-id");
        deleteConfirm("确定删除吗",id);
    }
    function deleteConfirm(alertInfo,id){
        myConfirmModal(alertInfo,function(){
            $.ajax({
                url:"deleteCoupon",
                type:"post",
                data:{"ids":id},
                dataType:"json",
                success:function(json,statusText){
                    if(json.errorCode == 0){
                        if(currentPage !=1 && total_count % pageSize == 1){//非首页且末页记录数为1时
                            currentPage = currentPage - 1;
                        }
                        render(true,currentPage,pageSize);
                    }else if(json.errorCode == 1){
                        responseTip(json.errorCode,json.errorInfo,1500);
                    }else if(json.errorCode == 2){
                        //优惠券已被领取且尚未使用时，删除前再确认
                        $("#myConfirmModal").modal('hide');
                        myConfirmModal(json.errorInfo,function(){
                        	$("#deleteConfirmModal").modal('hide');
                            //确认删除
                            $.ajax({
                                url:"deleteCoupon",
                                type:"post",
                                data:{"ids":id,"isAgree":1},
                                dataType:"json",
                                success:function(json,statusText){
                                    if(json.errorCode == 0){
                                        if(currentPage !=1 && total % pageSize == 1){//非首页且末页记录数为1时
                                            currentPage = currentPage - 1;
                                        }
                                        render(true,currentPage,pageSize);
                                    }else if(json.errorCode == 1){
                                        responseTip(json.errorCode,json.errorInfo,1500);
                                    }
                                },
                                error:errorResponse
                            });
                        },'#deleteConfirmModal');
                    }
                },
                error:errorResponse
            });
        });
    }
    init();
});